package cn.itcast;

import com.mysql.cj.jdbc.MysqlDataSource;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@EnableWebMvc
@Configuration
@ComponentScan
@EnableJpaRepositories("cn.itcast")
@EnableTransactionManagement
@PropertySource("classpath:wu.properties")// 增加属性源
public class JdbcSource {


        private final Environment env;

        public JdbcSource(Environment env) {
            this.env = env;
        }

        // 配置MySql数据源
        @Bean
        @Primary// 设置主数据库
        public DataSource jdbcDataSource() {

            MysqlDataSource source = new MysqlDataSource();
            // 从属性文件读取属性值
            source.setUrl(env.getProperty("wu.datasource.url"));
            source.setUser(env.getProperty("wu.datasource.username"));
            source.setPassword(env.getProperty("wu.datasource.password"));// 读取属性文件中的password属性
            return source;
        }

        // 配置entityManagerFactory
        @Bean
        public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {

            HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
            vendorAdapter.setGenerateDdl(true);
            // 显示sql语句
            vendorAdapter.setShowSql(true);
            vendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL8Dialect");// Mysql 8.X

            LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
            factory.setJpaVendorAdapter(vendorAdapter);

            factory.setPackagesToScan("cn.itcast");

            factory.setDataSource(dataSource);
            return factory;
        }

    // 配置事务
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {

        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }
    }
